package mwa.cs.sm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.AddressDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.dao.SitesDAO;
import mwa.cs.database.Database;
import mwa.cs.model.Sites;
import mwa.cs.util.JDate;

/**
 * Servlet implementation class CS11001Srvl
 */
public class CS11001Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private Database db ;
	private String vaUrlAddress;
	private String vaAgentBrowser;
	private int vnSiteId;
	private int vnUserId;
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS11001Srvl() {
        super();
       
    }
    public void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	String vaProcessType = request.getParameter("process_type");
    	
		vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
    	if(vaProcessType.equals("checkSitesData")){
    		checkSitesData(request,response);
    	}else if(vaProcessType.equals("getSitesData")){
    		getSitesData(request,response);
    	}else if(vaProcessType.equals("getProvince")){
    		getProvince(request,response);
    	}else if (vaProcessType.equals("getDistrict")){
    		getDistrict(request,response);
    	}else if(vaProcessType.equals("getCityCode")){
    		getCityCode(request,response);
    	}else if(vaProcessType.equals("update")){
    		updateData(request,response);
    	}else if (vaProcessType.equals("insert")){
    		insertData(request,response);
    	}
    	
    }
    public void insertData(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		String vaSiteName = request.getParameter("siteName");
		String vaHeadName = request.getParameter("headName");
		String vaHeadPosition = request.getParameter("HeadPosition");
		String vaTaxId = request.getParameter("TaxId");
		String vaTaxBranch = request.getParameter("TaxBranch");
		String vaHomeNumber = request.getParameter("HomeNumber");
		String vaAddress = request.getParameter("Address");
		String vaPostCode = request.getParameter("PostCode");
		String vaTelephone = request.getParameter("Telephone");
		String vaFax = request.getParameter("Fax");
		String vaProvince = request.getParameter("Province");
		String vaDistrict = request.getParameter("District");
		String vaCityCode = request.getParameter("CityCode");
		
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
    	this.db = new Database();
    	Sites voSites = new Sites();
    	voSites.setVnSiteId(vnSiteId);
    	voSites.setVaSiteName(vaSiteName);
    	voSites.setVaHeadName(vaHeadName);
    	voSites.setVaHeadPosition(vaHeadPosition);
    	voSites.setVaTaxId(vaTaxId);
    	voSites.setVaTaxBranch(vaTaxBranch);
    	voSites.setVaHomeNumber(vaHomeNumber);
    	voSites.setVaAddress(vaAddress);
    	voSites.setVaPostCode(vaPostCode);
    	voSites.setVaTelephone(vaTelephone);
    	voSites.setVaFax(vaFax);
    	voSites.setVaProvinceCode(vaProvince);
    	voSites.setVaDistrictCode(vaDistrict);
    	voSites.setVaCityCode(vaCityCode);
    	voSites.setVnInsertUserId(vnUserId);
    	voSites.setVaInsertDate(vaDate);
    	voSites.setVaInsertTime(vaTime);
    	
    	SitesDAO daoSitesDAO = new SitesDAO(db);
    	try {
    		
    		db.beginTransaction();
        	daoSitesDAO.addSites(voSites);
        	db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS11001", JDate.getDate(), JDate.getTime(),vnUserId, "CS11001Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		} finally{
			db.close();
		}
    	response.getWriter().write("insert_sucess");
    }
    public void updateData(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");		
		String vaSiteName = request.getParameter("siteName");
		String vaHeadName = request.getParameter("headName");
		String vaHeadPosition = request.getParameter("HeadPosition");
		String vaTaxId = request.getParameter("TaxId");
		String vaTaxBranch = request.getParameter("TaxBranch");
		String vaHomeNumber = request.getParameter("HomeNumber");
		String vaAddress = request.getParameter("Address");
		String vaPostCode = request.getParameter("PostCode");
		String vaTelephone = request.getParameter("Telephone");
		String vaFax = request.getParameter("Fax");
		String vaProvince = request.getParameter("province");
		String vaDistrict = request.getParameter("district");
		String vaCityCode = request.getParameter("cityCode");
		
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
    	this.db = new Database();
    	
    	Sites voSites = new Sites();
    	voSites.setVnSiteId(vnSiteId);
    	voSites.setVaSiteName(vaSiteName);
    	voSites.setVaHeadName(vaHeadName);
    	voSites.setVaHeadPosition(vaHeadPosition);
    	voSites.setVaTaxId(vaTaxId);
    	voSites.setVaTaxBranch(vaTaxBranch);
    	voSites.setVaHomeNumber(vaHomeNumber);
    	voSites.setVaAddress(vaAddress);
    	voSites.setVaPostCode(vaPostCode);
    	voSites.setVaTelephone(vaTelephone);
    	voSites.setVaFax(vaFax);
    	voSites.setVaProvinceCode(vaProvince);
    	voSites.setVaDistrictCode(vaDistrict);
    	voSites.setVaCityCode(vaCityCode);
    	voSites.setVnUpdateUserId(vnUserId);
    	voSites.setVaUpdateDate(vaDate);
    	voSites.setVaUpdateTime(vaTime);
    	
    	SitesDAO voSitesDAO = new SitesDAO(db);
    	try {
    		db.beginTransaction();
        	voSitesDAO.updateSites(vnSiteId, voSites);
        	db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS11001", JDate.getDate(), JDate.getTime(),vnUserId, "CS11001Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		}finally{
			db.close();
		}
    	response.getWriter().write("update_success");
    	
    }
    public void getCityCode(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		String vaProvince = request.getParameter("proVince");
		String vaDistrict = request.getParameter("disTrict");
		String[] vaMessage = null, vaValue = null;
		Database db = new Database();
    	
    	AddressDAO voAddress = new AddressDAO(db);
    	try {
    		List<Map<String, Object>> voResult = voAddress.findCity(vaProvince, vaDistrict);
    		
    		vaValue = new String[voResult.size()];
    		vaMessage = new String[voResult.size()];
    		for (int i = 0; i < voResult.size(); i++) {
    			Map<String, Object> voObject = voResult.get(i);	
    			vaValue[i] = (String) voObject.get("CITY"); 
    			vaMessage[i] = (String) voObject.get("NAME");
    		}	
    		JSONObject voObject = new JSONObject();
    		JSONArray voList = new JSONArray();
    		PrintWriter voOut = response.getWriter();
    		if (vaMessage != null) {
    			for (int i = 0; i < vaMessage.length; i ++) {
    				voList.add(vaMessage[i]);
    			}
    		}
    		voObject.put("messages", voList);
    		JSONArray voList2 = new JSONArray();
    		if (vaValue != null) {
    			for (int i = 0; i < vaValue.length; i ++) {
    				voList2.add(vaValue[i]);
    			}
    		}

    		voObject.put("values", voList2);
    		
    		voOut.print(voObject.toJSONString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			db.close();
		}

    }
    
    public void getDistrict(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		String vaProvince = request.getParameter("proVince");
		
		String[] vaMessage = null, vaValue = null;
    	this.db = new Database();
    	
    	AddressDAO voAddress = new AddressDAO(db);
		List<Map<String, Object>> voResult = voAddress.findDistrict(vaProvince);
		vaValue = new String[voResult.size()];
		vaMessage = new String[voResult.size()];
		for (int i = 0; i < voResult.size(); i++) {
			Map<String, Object> voObject = voResult.get(i);	
			vaValue[i] = (String) voObject.get("DISTRICT"); 
			vaMessage[i] = (String) voObject.get("NAME");
			//System.out.println(vaValue[i]+"  "+vaMessage[i]);
		}
		JSONObject voObject = new JSONObject();
		JSONArray voList = new JSONArray();
		PrintWriter voOut = response.getWriter();
		if (vaMessage != null) {
			for (int i = 0; i < vaMessage.length; i ++) {
				voList.add(vaMessage[i]);
			}
		}
		voObject.put("messages", voList);
		JSONArray voList2 = new JSONArray();
		if (vaValue != null) {
			for (int i = 0; i < vaValue.length; i ++) {
				voList2.add(vaValue[i]);
			}
		}
		voObject.put("values", voList2);
		
		db.close();
		voOut.print(voObject.toJSONString());
		
    }
    
    
    public void getProvince(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
    	String vaProvince = request.getParameter("province");
    	String[] vaMessage = null, vaValue = null;
    	this.db = new Database();
    	if (vaProvince != null && vaProvince.equals("yes")) {
			AddressDAO voAddress = new AddressDAO(db);
			List<Map<String, Object>> voResult = voAddress.findProvince();
			vaValue = new String[voResult.size()];
			vaMessage = new String[voResult.size()];
			for (int i = 0; i < voResult.size(); i++) {
				Map<String, Object> voObject = voResult.get(i);	
				vaValue[i] = (String) voObject.get("PROVINCE"); 
				vaMessage[i] = (String) voObject.get("NAME");	
				//System.out.println(vaValue[i]+"  "+vaMessage[i]);
			}
    	}
    	JSONObject voObject = new JSONObject();
		JSONArray voList = new JSONArray();
		PrintWriter voOut = response.getWriter();
		if (vaMessage != null) {
			for (int i = 0; i < vaMessage.length; i ++) {
				voList.add(vaMessage[i]);
			}
		}
		voObject.put("messages", voList);
		JSONArray voList2 = new JSONArray();
		if (vaValue != null) {
			for (int i = 0; i < vaValue.length; i ++) {
				voList2.add(vaValue[i]);
			}
		}
		voObject.put("values", voList2);
		
		db.close();
		voOut.print(voObject.toJSONString());
		
    }
    
    
    
    public void checkSitesData(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		
		SitesDAO voSitesDAO = new SitesDAO(db);
		 Map<String, Object>  voMap =voSitesDAO.findSitesBySiteId(vnSiteId);
		 
		 db.close();
		if(voMap == null){
			response.getWriter().write("site_no_value");
		}else{
			response.getWriter().write("success");
			
		}
		
		//response.getWriter().write("site_no_value");
    }
    
    
    public void getSitesData(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    		
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		this.db = new Database();
		
		SitesDAO daoSitesDAO = new SitesDAO(db);
		 Map<String, Object>  voMap =daoSitesDAO.findSitesBySiteId(vnSiteId);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("siteId",voMap.get("SITE_NAME") ==null?"":voMap.get("SITE_NAME").toString());
		jsonObject.put("siteName",voMap.get("HEAD_NAME")==null?"":voMap.get("HEAD_NAME").toString());
		jsonObject.put("headName",voMap.get("HEAD_POSITION")==null?"":voMap.get("HEAD_POSITION").toString());
		jsonObject.put("taxId",voMap.get("TAX_ID")==null ?"":voMap.get("TAX_ID").toString());
		jsonObject.put("branchTax",voMap.get("TAX_BRANCH")==null?"":voMap.get("TAX_BRANCH").toString());
		jsonObject.put("homeNumber",voMap.get("HOME_NUMBER")==null ?"":voMap.get("HOME_NUMBER").toString());
		jsonObject.put("address",voMap.get("ADDRESS")==null ?"" :voMap.get("ADDRESS").toString());
		jsonObject.put("postCode",voMap.get("POST_CODE")==null ?"" :voMap.get("POST_CODE").toString());
		jsonObject.put("telephone",voMap.get("TELEPHONE")==null ?"" :voMap.get("TELEPHONE").toString());
		jsonObject.put("fax",voMap.get("FAX")==null ?"" :voMap.get("FAX").toString());
		jsonObject.put("province",voMap.get("PROVINCE_CODE")==null?"" :voMap.get("PROVINCE_CODE").toString());
		jsonObject.put("district",voMap.get("DISTRICT_CODE")==null?"" :voMap.get("DISTRICT_CODE").toString());
		jsonObject.put("cityCode",voMap.get("CITY_CODE")==null?"" :voMap.get("CITY_CODE").toString());
		
		db.close();
		response.getWriter().print(jsonObject.toJSONString());
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			processRequest(request,response);
	}

}
